<template>
  <view class="content">
    <h2 class="loading__text">
      {{ page.tip }}
    </h2>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { UniStore } from '@/utils/UniStorege'
import { useLoginStore } from '@/store/LoginStore'
import { UniTool } from '@/utils/UniTool'
import { StringUtils } from '@/utils/StringUtils'
import { reactive } from 'vue'

const tips = {
  0: '正在跳转页面...',
  1: '正在自动登录...'
}

const page = reactive({
  tip: ''
})

const setTipState = function (type) {
  page.tip = tips[type]
}

console.log('load redirect page')

const logStore = useLoginStore()

const loginWithCache = async function (autoLogin) {
  let loginInfo
  if (autoLogin) {
    loginInfo = {
      username: '',
      password: ''
    }
  } else {
    loginInfo = UniStore.getObject('u_201')
  }
  let { username = '', password = '' } = loginInfo || {}
  if (StringUtils.isEmptyOrNull(username) || StringUtils.isEmptyOrNull(password)) {
    // uni.showToast({
    //   title: '自动登录失效,请重新登录!'
    // })
    return false
  }
  const token = UniStore.getT()
  console.log(token)
  if (StringUtils.isEmptyOrNull(token)) {
    uni.reLaunch({
      url: '/pages/login/index'
    })
    return false
  }
  try {
    let res = await logStore.login({
      username,
      password
    })

    let { success = false, msg = '' } = res
    if (!success) {
      return
    }

    return true
  } catch (err) {
    uni.reLaunch({
      url: 'pages/login/index'
    })
    console.error('登录失败,请重新登录')
  }
}

onLoad(async () => {
  console.log('load redirect page')
  // #ifdef APP
  console.log('cache cleared')
  plus.cache.clear()
  // #endif
  const page = {
    main: '../main/index',
    appMain: '../AppMain/index',
    manuf: '../ManufactureManagement/MFGIndex',
    login: '../login/index'
  }

  setTipState(1)
  let isAutoLogin = await loginWithCache()
  if (isAutoLogin) {
    uni.redirectTo({
      url: page.appMain
    })
    return
  }
  setTipState(1)
  uni.redirectTo({
    url: page.login
  })
})

onShow(() => {})
</script>

<style lang="scss"
       scoped>
.content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
